package com.jfzt.hgroup.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author erxiang.chen
 * @Date: 2024/4/12 11:14
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public String handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuffer stringBuffer = new StringBuffer();
        bindingResult.getFieldErrors().forEach(item -> {
            String message = item.getDefaultMessage();
            stringBuffer.append(message);
        });
        String message = e.getCause() != null ? e.getCause().getMessage() : e.getMessage();

        log.info(System.currentTimeMillis() + " ERROR " + e.getClass().getPackageName() + ": " + message);
        return "逮住异常 数据效验 MethodArgumentNotValidException";
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public String handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e) {
        String message = e.getCause() != null ? e.getCause().getMessage() : e.getMessage();

        log.info(System.currentTimeMillis() + " ERROR " + e.getClass().getPackageName() + ": " + message);
        return "逮住异常 请求方式不支持 HttpRequestMethodNotSupportedException";
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(BaseException.class)
    public String handleServiceException(BaseException e) {
        int code = Integer.parseInt(e.getCode());
        String message = e.getCause() != null ? e.getCause().getMessage() : e.getMessage();

        log.info(System.currentTimeMillis() + " ERROR " + e.getClass().getPackageName() + ": " + message);

        return "逮住异常 BaseException";
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public String handleRuntimeException(RuntimeException e) {
        String message = e.getCause() != null ? e.getCause().getMessage() : e.getMessage();
        log.info(System.currentTimeMillis() + " ERROR " + e.getClass().getPackageName() + ": " + message);
        return "逮住异常  系统内部错误 RuntimeException";
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        String message = e.getMessage();

        log.info(System.currentTimeMillis() + " ERROR " + e.getClass().getPackageName() + ": " + message);
        return "逮住异常 Exception";
    }
}

